package com.atguigu.chapter10;

import com.atguigu.bean.LoginEvent;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * Author: Pepsi
 * Date: 2023/8/14
 * Desc:
 */


/*
*
* 用户恶意登录
*   这个案例对于恶意的定义是：2秒内连续登录失败就是恶意登录
*
* */


public class Flink07_Project_High_illegalLogin {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        KeyedStream<LoginEvent, Long> stream = env
//                .readTextFile("input/LoginLog.csv")
                .socketTextStream("hadoop101",9999)
                .map(line -> {
                    String[] data = line.split(",");
                    return new LoginEvent(
                            Long.valueOf(data[0]),
                            data[1],
                            data[2],
                            Long.parseLong(data[3]) * 1000
                    );
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((login, ts) -> login.getEventTime())
                )
                // 先以用户id分组，
                .keyBy(LoginEvent::getUserId);

        Pattern<LoginEvent, LoginEvent> pattern = Pattern
                .<LoginEvent>begin("fail")
                .where(new SimpleCondition<LoginEvent>() {
                    @Override
                    public boolean filter(LoginEvent value) throws Exception {
                        return "fail".equals(value.getEventType());
                    }
                })
                .times(2)
                .consecutive()
                // 设置超时时间  前面两个数据时间间隔小于等于2s
                .within(Time.milliseconds(2001));

        PatternStream<LoginEvent> ps = CEP.pattern(stream, pattern);

        ps
                .select(new PatternSelectFunction<LoginEvent, String>() {
                    @Override
                    public String select(Map<String, List<LoginEvent>> pattern) throws Exception {
                        return pattern.get("fail").get(0).getUserId()+ " 正在恶意登录...";
                    }
                })
                .print();

        /*
        *
        *   1036,83.149.9.216,fail,1558430842
            1036,83.149.9.216,fail,1558430843
            1036,83.149.9.216,fail,1558430844
            1036,83.149.9.216,fail,1558430845
            1036,83.149.9.216,fail,1558430846
            1036,83.149.9.216,fail,1558430847

             * 为啥这样输入，到7才会输出1036恶意登录？
             因为第一个时间是2，然后2s内有失败触发，也就是<=4s才会触发，
             * 当事件时间到4的时候，水印更新到了  4-3=1
             * 当  。。。。5       水印       5-3=2
             * 当  。。。。6       水印       6-3=3
             * 当  。。。。7       水印       7-3=4  这个时候才触发
        *
        * */





        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
